﻿//++
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
// Module Name:
//
//  ExecuteDelegateTask.cs
//    
// Abstract:
//
//  This module implements the ExecuteDelegateTask class. This handles the task of executing a given delegate.
//
//--

using System;
using System.Diagnostics;

using Microsoft.OfficeCommunicationsServer.Applications.Common;

namespace Microsoft.EnhancedReminders.Scheduler
{
    /// <summary>
    /// Delegate for this task.
    /// </summary>
    /// <param name="taskContext">Task context</param>
    /// <param name="state">State associated with the delegate</param>
    internal delegate void TaskDelegate(TaskContext taskContext, object state);
    
    /// <summary>
    /// This handles the task of executing a given delegate.
    /// </summary>
    internal class ExecuteDelegateTask : Task
    {
        // Delegate to be executed by this task
        private readonly TaskDelegate _taskDelegate;

        // State associated with the delegate
        private readonly object _state;

        /// <summary>
        /// ctor.
        /// </summary>
        /// <param name="taskContext">Task context</param>
        /// <param name="taskDelegate">Delegate to be executed</param>
        /// <param name="state">State associated with the delegate</param>
        internal ExecuteDelegateTask(TaskContext taskContext, TaskDelegate taskDelegate, object state)
            : base(taskContext)
        {
            Debug.Assert(taskDelegate != null, "taskDelegate != null");

            _taskDelegate = taskDelegate;
            _state = state;
        }

        /// <summary>
        /// Invokes the delegate associated with this task.
        /// </summary>
        internal override void Begin()
        {
            _taskDelegate.Invoke(_taskContext, _state);

            // This task completes synchronously
            RaiseCompleted(new TaskCompletedEventArgs(_taskContext));
        }
    }
}
